const http = require('http');
const fs = require('fs');
var path = require('path')
var Context = require("yunos/cloudfs/Context").getInstance();
var PublicDir = require("yunos/cloudfs/Context").PublicDir;

const logger = log("FileUploadByNode")

class FileHelp {
    constructor(){
        this.formatList = {
            ".jpg": "image/jpeg",
            ".txt": "text/plain"
        }
        this.uploadOptions = {
            hostname: '192.168.0.148',
            port: 8192,
            path: '/upload',
            method: 'POST',
            headers:{

            }
        }
        this.downloadUrl = "http://192.168.0.148:8192/download";
        this.downloadSavePath = Context.getPublicDir(PublicDir.Downloads);
    }
    fileUpload(filePath){
        try{
            //生成分隔数据
            var boundaryKey = '----' + new Date().getTime();    // 用于标识请求数据段
            this.uploadOptions.headers = {
                'Content-Type': 'multipart/form-data; boundary=' + boundaryKey,
                'Connection': 'keep-alive'
            }
            let fileName = path.basename(filePath)
            let extName = 	path.extname(filePath)
            var self = this
            //读取需要上传的文件内容
            fs.readFile(filePath, function (err, data) {
                var head = '--' + boundaryKey + '\r\n' + 'Content-Disposition:form-data; name="file"; filename="'+fileName+'"\r\n' + 'Content-Type:'+self.formatList[extName]+'\r\n\r\n';
                var content = data
                var footer = '\r\n--' + boundaryKey + '--';
                //发送请求
                var req = http.request(self.uploadOptions, function (res) {
                    res.setEncoding('utf8');
                    res.on('data', function (chunk) {
                        logger.F('body:' + chunk);
                    });

                });
                req.on('error', function(e) {
                    logger.F("error:"+e);
                });
                req.write(head);
                req.write(content);
                req.write(footer)
                req.end();
            });
        }catch(err){
            logger.F("error：",err);
        }
    }
    downloadFile(fileName){
        let url = this.downloadUrl + '?filename=' + fileName;
        http.get(url, (res) => {
          const { statusCode } = res;
          let error;
          if (statusCode !== 200) {
            error = new Error('请求失败\n' +
                              `状态码: ${statusCode}`);
          }
          if (error) {
            logger.F("终止请求：",error.message);
            // 消费响应数据来释放内存。
            res.resume();
            return;
          }

          res.setEncoding('binary');
          let rawData = Buffer.alloc(0);
          res.on('data', (chunk) => {
            //    rawData += chunk;
               rawData =  Buffer.concat([rawData,chunk]);
           });
          res.on('end', () => {
            try {
              let savePath = this.downloadSavePath+ "/" + fileName;
              logger.F("保存目录:" + savePath);
              logger.F("文件长度",rawData.length)
              fs.writeFile(savePath, rawData, "binary", function(err){
                  if(err){
                      logger.F(error);
                      logger.F("down fail");
                  }
                  logger.F("down success");
              });
            } catch (e) {
              logger.F(e.message);
            }
          });
        }).on('error', (e) => {
          logger.F(`出现错误: ${e.message}`);
        });
    }
    // downloadFile(fileName){
    //     try{
    //         let url = this.downloadUrl + '?filename=' + fileName;
    //         let savePath = this.downloadSavePath+ "/" + fileName;
    //         let stream = fs.createWriteStream(savePath);
    //         request(url).pipe(stream).on("close", function (err) {
    //             logger.F("文件[" + fileName + "]下载完毕");
    //         });
    //     }catch(error){
    //         logger.F(error)
    //     }
    // }
}

module.exports = FileHelp;
